﻿
using bitzhuwei.PreDirectiveFormat;
using System.Text;

namespace bitzhuwei.PreDirective.TestConsole {
    internal class Program {
        static void Main(string[] args) {
            Console.WriteLine("Hello, PreDirectiveFormat Console!");
            var compiler = new bitzhuwei.PreDirectiveFormat.CompilerPreDirective();
            var searchPattern = "*";
            var shaderFiles = Directory.GetFiles(@".\..\..\..\testcase-codes", searchPattern, SearchOption.AllDirectories);
            foreach (var fileName in shaderFiles) {
                var tail = fileName.ToLower();
                if (!(tail.EndsWith(".glsl"))) {
                    continue;
                }
                Console.WriteLine($"Processing {fileName}");
                var allText = File.ReadAllText(fileName);
                var ppContext = new PpContext();
                using (var writer = new StreamWriter($"{fileName}.tree"))
                using (var reader = new StringReader(allText)) {
                    while (true) {
                        var line = reader.ReadLine();
                        if (line == null) { break; }
                        var tokens = compiler.Analyze(line);
                        if (tokens.Error) { throw new Exception(tokens.ToString()); }
                        var syntaxTree = compiler.Parse(tokens);
                        var preDirective = compiler.Extract(syntaxTree, tokens, allText,
                            tag: nameof(PpContext), obj: ppContext);
                        ArgumentNullException.ThrowIfNull(preDirective);
                        preDirective.Update(ppContext, tokens);
                        //syntaxTree.Print(writer, bitzhuwei.PreDirectiveFormat.CompilerPreDirective.stArray);
                        writer.WriteLine(line);
                        writer.WriteLine($"    active:{ppContext.isActive}");

                        //using (var writer = new StreamWriter($"{fileName}.format")) {
                        //    var context = new FormatContext(tabUnit: 4, tabCount: 0, tokens);
                        //    translationUnit.Format(writer, context);
                        //}
                        //using (var writer = new StreamWriter($"{fileName}.yield")) {
                        //    var context = new FormatContext(tabUnit: 4, tabCount: 0, tokens);
                        //    foreach (var item in translationUnit.YieldTokens(writer, context)) { }
                        //}
                        //using (var writer = new StreamWriter($"{fileName}.full")) {
                        //    var context = new FormatContext(tabUnit: 4, tabCount: 0, tokens);
                        //    translationUnit.FullFormat(new BlankConfig(inlineBlank: 0, forceNewline: false), writer, context);
                        //}
                    }
                }
            }

            Console.WriteLine("done.");
        }
    }
}
